import { CheckToken } from "@/api/base";
import { Dialog } from "vant";
import router from "@/router";
export default class tokenValidate {
  token = '';
  timer = null;
  start() {
    // 循环调用校验token的接口，当发现token过期后 停止调用
    if (this.timer) return;
		// 判断是否为开发环境，若是则加长请求时间
		const isDev = process.env.NODE_ENV === 'development';
		const intervalTime = isDev ? 200000 : 1000;
    this.timer = setInterval(async () => {
      this.token = localStorage.getItem("tokenKey");
      if (this.token) {
        const response = await CheckToken({ Token: this.token });
        // console.log(response);
        if (response.ErrorCode != 0) return;
        // 存在说明需要重新登录
        if (response.Result.IsLoginOverTime) {
          Dialog.alert({
            message: "登录信息已失效，请重新登录吗？",
            confirmButtonText: "重登",
          })
            .then(() => {
              router.replace({
                name: "login",
              });
            })
          localStorage.setItem("tokenKey", '')
          localStorage.setItem("token", '')
          this.stop();
        }
      }else{
        this.stop()
      }

    }, intervalTime);
  }
  stop(){
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }
}